/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:10:29
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-13 10:33:49
 */
import React from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import { routerShape } from 'react-router';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import {
  Spin,
  Icon,
  Modal,
  Button,
  Table,
  Tooltip,
  Row,
  Col,
  message,
} from 'antd';
import {
  WeaErrorPage,
  WeaTools,
  WeaAlertPage,
  WeaNewScroll,
  WeaTag,
  WeaTextarea,
  WeaLocaleProvider,
  WeaAvatar,
} from 'ecCom';
// import printJS from 'print-js';
// import Print from 'rc-print';

import {
  Collapse,
  DropdownMenu,
  PopoverTodo,
  PopoverAccount,
  ContentIframe,
} from './com';
import { getFlagCls, getFileTypeCls } from '../util/index';
import WeaCircleImage from '../public/wea-circle-image';

const getLabel = WeaLocaleProvider.getLabel;

const { confirm } = Modal;
const { tryCatch, viewer } = WeaTools;
const store = ['routing', 'emailMainStore', 'emailOpsStore'];

@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@5u13s5`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject(...store)
@observer
class View extends React.Component {
  static displayName = 'View';
  static contextTypes = {
    router: routerShape,
  };
  constructor(props) {
    super(props);
    this.prefixClass = 'wea-email-view';
    this.printId = `weaEmailPrint_${Math.random().toString(36).substr(2, 6)}`;
    this.state = {
      emailScroll: false,
      currentFont: 'small',
      fontSetting: {
        big: { fontSize: 1.5, name: '大', selected: false },
        mid: { fontSize: 1.2, name: '中', selected: false },
        small: { fontSize: 1, name: '默认', selected: true },
      },
    };
  }
  componentDidMount() {
    const { id } = this.getStoreNow();
    id !== 'init' && this.doInit(id);
  }
  componentWillReceiveProps(nextProps) {
    const { setState } = this.getStoreNow();
    setState({ showQuickReplay: false });
    const {
      id,
      location: {
        query: { id: _id },
      },
      viewType,
    } = this.props;
    const {
      id: idn,
      location: {
        query: { id: _idn },
      },
    } = nextProps;
    if (idn && id !== idn && idn !== 'init') {
      this.setState({ emailScroll: false });
      this.doInit(idn);
    } else if (
      (!id || !idn) &&
      viewType !== 'inList' &&
      _idn &&
      _id !== _idn &&
      _idn !== 'init'
    ) {
      this.setState({ emailScroll: false });
      this.doInit(_idn);
    }
  }
  componentWillUnmount() {
    const { setState } = this.getStoreNow();
    setState({ showQuickReplay: false });
    this.setState({ emailScroll: false });
  }

  reloadEmail = () => {
    const { id } = this.getStoreNow();
    id !== 'init' && this.doInit(id);
  };

  // on
  onIframeClick = () => {
    const { onIframeClick } = this.props;
    this.hide();
    typeof onIframeClick === 'function' && onIframeClick();
  };
  onSetTag = (ids, tagId, operation) => {
    const { onSetTag } = this.props;
    typeof onSetTag === 'function' && onSetTag(ids, tagId, operation);
  };
  onCollect = (ids, star) => {
    const { onCollect } = this.props;
    typeof onCollect === 'function' && onCollect(ids, star);
  };
  onSetReadStatus = (ids, status) => {
    const { onSetReadStatus } = this.props;
    typeof onSetReadStatus === 'function' && onSetReadStatus(ids, status);
  };

  // 邮件识别发票
  emailOcrInvoice(params) {
    const { emailOcrInvoice } = this.props;
    typeof emailOcrInvoice === 'function' && emailOcrInvoice(params);
  }

  onDeleteEmail = (ids, operate) => {
    const { onDeleteEmail } = this.props;
    typeof onDeleteEmail === 'function' && onDeleteEmail(ids, operate);
  };
  onMoveToFolder = (ids, folderid, isIn) => {
    const { onMoveToFolder } = this.props;
    typeof onMoveToFolder === 'function' && onMoveToFolder(ids, folderid, isIn);
  };
  onDropDownClick = (key, item) => {
    const {
      emailMainStore: { setState },
    } = this.props;
    const {
      id,
      baseInfo: { folderid, isInternal },
      getDropDown,
      getBaseInfo,
      getEmailRecallDetailList,
    } = this.getStoreNow();
    const { router } = this.context;
    if (id && id !== 'init') {
      if (/^\-?\d+$/.test(key)) {
        if (item.type === 'TAG') {
          // tag
          this.onSetTag([id], key, 'addLabel');
        } else {
          // folder
          this.onMoveToFolder([id], key, folderid === key);
        }
      } else if (key === 'cancelAllTag') {
        // tag
        this.onSetTag([id], '', 'cancelLabel');
      } else if (key === 'tagManager' || key === 'folderManager') {
        router.push(
          `main/email/setting/${
            key === 'tagManager'
              ? 'labelManage'
              : key === 'folderManager'
              ? 'folderManage'
              : ''
          }`,
        );
      } else if (key === 'markAsReaded' || key === 'markAsUnread') {
        this.onSetReadStatus([id], key === 'markAsReaded' ? 1 : 0);
      } else if (key === 'markAsStart' || key === 'markAsCancelStar') {
        this.onCollect([id], key === 'markAsStart' ? 1 : 0);
      } else if (key === 'delete' || key === 'remove') {
        confirm({
          content: getLabel(15097, '确定要删除吗？'),
          okText: getLabel(826, '确定'),
          onOk: () =>
            this.onDeleteEmail(
              [id],
              key === 'delete' ? 'delete' : 'deletePermanently',
            ),
        });
      } else if (key === 'markAsWaitdeal') {
        setState({ todoSetVisible: true, todoSetIds: [id] });
      } else if (
        key === 'reply' ||
        key === 'ReplyAll' ||
        key === 'topForward' ||
        key === 'topEditAgain' ||
        key === 'ReplyAll_file' ||
        key === 'reply_file'
      ) {
        const flag =
          key === 'reply'
            ? 1
            : key === 'ReplyAll'
            ? 2
            : key === 'reply_file'
            ? 6
            : key === 'ReplyAll_file'
            ? 7
            : key === 'topForward'
            ? 3
            : key === 'topEditAgain'
            ? 5
            : '';
        router.push({
          pathname: 'main/email/new',
          query: { isInternal, id, flag },
        });
      } else if (key === 'createAndMoveTo') {
        this.onMoveToFolder([id], key, false);
      } else if (key === 'createAndTagIt') {
        this.onSetTag([id], key, 'labelCreate');
      } else if (key === 'topRecall') {
        confirm({
          content: getLabel(
            505366,
            '撤回操作不可恢复，确定要撤回已发送邮件吗？',
          ),
          okText: getLabel(826, '确定'),
          onOk: () => {
            const {
              emailOpsStore: { recall },
              refreshList,
            } = this.props;
            recall({ mailId: id }).then((res) => {
              if (res.status === '1') {
                getBaseInfo({ mailId: id });
                getDropDown({ mailId: id });
                getEmailRecallDetailList(id);
                if (refreshList && typeof refreshList === 'function') {
                  refreshList();
                }
              }
            });
          },
        });
      } else if (key === 'exportToDoc') {
        this.onExportToDoc([id]);
      } else if (key === 'exportToCustomerContact') {
        this.onExportToCrm([id]);
      } else if (key === 'exportToEML') {
        this.onExportToEml([id]);
      } else if (key === 'exportToHtml') {
        this.onExportToHtml([id]);
      } else if (key === 'printMail') {
        this.onPrintEmail([id]);
        // this.refs.content.refs.contentWindow.print();
        // this.refs.printArea.onPrint();
        // printJS(this.printId, 'html');
      } else {
        confirm({ content: getLabel('506455', '功能开发中') });
      }
    }
  };
  onExportToDoc = (ids) => {
    const { onExportToDoc } = this.props;
    typeof onExportToDoc === 'function' && onExportToDoc(ids);
  };
  onExportToCrm = (ids) => {
    const { onExportToCrm } = this.props;
    typeof onExportToCrm === 'function' && onExportToCrm(ids);
  };
  onExportToEml = (ids) => {
    const { onExportToEml } = this.props;
    typeof onExportToEml === 'function' && onExportToEml(ids);
  };

  onExportToHtml = (ids) => {
    const { onExportToHtml } = this.props;
    typeof onExportToHtml === 'function' && onExportToHtml(ids);
  };

  onPrintEmail = (ids) => {
    const { onPrintEmail } = this.props;
    typeof onPrintEmail === 'function' && onPrintEmail(ids);
  };
  onTodoClick = (todoSetIds, params = {}) => {
    const { onTodoClick } = this.props;
    typeof onTodoClick === 'function' && onTodoClick(todoSetIds, params);
  };
  onTodoComplete = async (mailIds) => {
    const { onTodoComplete } = this.props;
    typeof onTodoComplete === 'function' && onTodoComplete(mailIds);
  };
  onUnReadedListClick = (unReadedListId) => {
    const {
      emailMainStore: { setState },
    } = this.props;
    const {
      baseInfo: { originalMailId },
      getReadCount,
    } = this.getStoreNow();
    const params = {
      mailId: unReadedListId,
      originalMailId,
      readed: '',
    };
    getReadCount(params).getReadList(params);
    setState({ unReadedListVisible: true, unReadedListId });
  };
  async doInit(mailId) {
    const storeNow = this.getStoreNow(mailId);
    const res = await storeNow.getRight({ mailId });
    if (res.viewRight === 1) {
      storeNow
        .getBaseInfo({ mailId }, ({ subjectText }) => {
          const {
            emailMainStore: { setState, tabInfo },
          } = this.props;
          setState({
            tabInfo: toJS(tabInfo).map(t => ({
              ...t,
              title: t.tabKey === mailId ? subjectText : t.title,
            })),
          });

          // 需要回执的才调用此处
          const { baseInfo } = storeNow;
          const { isInternal, isSendApart, recallstate } = baseInfo;
          if (baseInfo.receiveNeedReceipt === 1) {
            this.receiveNeedReceipt(mailId);
          }

          // 获取完baseinfo再获取分别发送结果列表 && 只有在外部邮件并且分别发送时才请求
          isInternal === 0 &&
            isSendApart === 1 &&
            storeNow.getSendApartResultList(mailId);
          // 获取完baseinfo再获取撤回邮件结果列表 && 只有在内部邮件并且已撤回时才请求
          isInternal === 1 &&
            recallstate === 1 &&
            storeNow.getEmailRecallDetailList(mailId);
        })
        .getDropDown({ mailId })
        .getContent({ mailId });
    }
  }
  // onScrollToFiles() {
  //   const { id } = this.getStoreNow();
  //   const dom = this.refs[`weaNewView_${id}`];
  //   const scroller = $(dom).closest('.scroller');
  //   scroller.animate({ scrollTop: $(dom).height() - scroller.height() + 50 });
  // }
  // get
  hide = (isViewScroll = false) => {
    const { account, todo, collapseTo, collapseCc } = this.refs;
    account && account.hide();
    todo && todo.hide();
    collapseTo && collapseTo.hide();
    collapseCc && collapseCc.hide();
    if (isViewScroll) {
      let scrollTop = this.refs.scroll.getScrollTop();
      this.setState({ emailScroll: scrollTop > 0 });
    }
  };
  getStoreNow(idc) {
    const {
      emailMainStore,
      id,
      location: {
        query: { id: _id },
      },
    } = this.props;
    const viewId = idc || id || _id || 'init';
    emailMainStore.addViewStore(viewId);
    const { viewStores } = emailMainStore;
    return viewStores[viewId];
  }

  listArray = (arr) => {
    let tempArr = arr.map((item) => {
      if (item.showName === '' && item.type === 'group') {
        item.showName = getLabel('506456', '(该组已被删除)');
      }
      return item;
    });
    return tempArr;
  };

  setIframeFont = (font) => {
    const dom = this.refs.content && this.refs.content.refs.content;
    if (dom) {
      const document = dom.contentDocument;
      const html = document.getElementsByTagName('html')[0];
      const body = document.getElementsByTagName('body')[0];
      html.style.fontSize = `${font}rem`;
      body.style.fontSize = `${font}rem`;
    }
  };

  setCurrentFont = (fontkey) => {
    // console.log('key', fontkey);
    let newFont = { ...this.state.fontSetting };
    for (let key in newFont) {
      if (key === fontkey) {
        newFont[key].selected = true;
      } else {
        newFont[key] = { ...newFont[key], selected: false };
      }
    }
    // console.log('newFont', newFont)
    this.setState({ fontSetting: newFont, currentFont: fontkey });
    this.setIframeFont(this.state.fontSetting[fontkey].fontSize);
  };

  onEmailOcrInvoiceClick = (e) => {
    const { baseInfo } = this.getStoreNow();
    const { id } = baseInfo;
    if (emailOcrInvoiceStatus === '0') {
      this.emailOcrInvoice({ mailid: id });
      e.stopPropagation && e.stopPropagation();
      e.preventDefault && e.preventDefault();
      e.nativeEvent && e.nativeEvent.preventDefault();
    }
  };

  getBase() {
    const { baseInfo, isSimple, setState } = this.getStoreNow();
    if (!baseInfo.fromSpan) return null;
    const {
      id,
      toSpan,
      ccSpan,
      bccSpan,
      subject,
      senddate,
      senddateSpan,
      labels,
      waitdeal,
      starred,
      unReadedCount,
      op_showUnReadedCount,
      waitdealBean,
      fileInfos: { count },
      bccTipInfo,
      belongtoType,
      belongtoInfo,
      isInternal,
      classification,
      classificationSpan,
      emailOcrInvoiceStatus,
    } = baseInfo;
    let { fromSpan } = baseInfo;
    if (isInternal === 1) {
      fromSpan = {
        ...fromSpan,
        ...{ typeValue: fromSpan.hrmId, type: 'resource' },
      };
    }
    const { imageUrl, showName, hrmId } = fromSpan;
    const regName = /([\s\S]*)(\<[\S\s]+\>$)/;
    const nameSpan = !regName.test(showName) ? (
      <span style={{ cursor: 'pointer' }}>{showName}</span>
    ) : (
      <a className="isExtraEmail">
        {showName.match(regName)[1]}
        <span>{showName.match(regName)[2]}</span>
      </a>
    );

    let headerProps = { name: showName, url: imageUrl, userId: hrmId };
    const list = [
      <div className={`${this.prefixClass}-base-send`}>
        {isInternal === 1 ? (
          <div className="wea-email-avatar">
            <WeaAvatar
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaAvatar@1zqxmb@emailinternalavatar`}
              {...headerProps}
              style={{ width: 40, height: 40 }}
            />
          </div>
        ) : null}
        {isInternal !== 1 ? (
          <div className="wea-email-avatar">
            <WeaCircleImage
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaCircleImage@dpd4k7@emailouteravatar`}
              diameter={40}
              src={imageUrl || ''}
              name={showName || ''}
            />
          </div>
        ) : null}

        {fromSpan.hrmId !== '1' ? (
          <PopoverAccount
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_PopoverAccount@3hq1b0@emailaccounts`}
            ref="account"
            data={fromSpan}
            reloadEmail={this.reloadEmail}
          >
            {nameSpan}
          </PopoverAccount>
        ) : (
          <span style={{ cursor: 'pointer' }}>{showName}</span>
        )}
        <span style={{ marginLeft: 10 }} title={senddateSpan}>
          {senddate}
        </span>
        <div className={`${this.prefixClass}-base-send-ops`}>
          {belongtoType !== '' ? (
            <Tooltip
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Tooltip@vqc5ei@emailbelongtoType`}
              title={`${belongtoInfo.name}|${belongtoInfo.department}|${belongtoInfo.job}`}
              placement="left"
            >
              {belongtoType * 1 === 1 ? (
                <i
                  className="icon-coms02-Main-account-number"
                  style={{ color: '#F5A623' }}
                />
              ) : belongtoType * 1 === 2 ? (
                <i
                  className="icon-coms02-Secondary-account-number"
                  style={{ color: 'grey' }}
                />
              ) : (
                ''
              )}
            </Tooltip>
          ) : (
            ''
          )}
          {waitdeal ? (
            <PopoverTodo
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_PopoverTodo@u1lo0t@waitdeal`}
              ref="todo"
              data={waitdealBean}
              onTodoClick={p =>
                this.props.onTodoClick([id], { ...waitdealBean, ...p })
              }
              onTodoComplete={() => this.props.onTodoComplete([id])}
            >
              <span title={getLabel(384239, '查看待办信息')}>
                <i className={getFlagCls('agency', 'n')} />
              </span>
            </PopoverTodo>
          ) : (
            <i
              className={getFlagCls('agency', 'o')}
              title={getLabel(384240, '设置待办')}
              onClick={() => this.onTodoClick([id.toString()])}
            />
          )}
          <i
            className={getFlagCls('fav', starred ? 'n' : 'o')}
            title={
              starred
                ? getLabel(81297, '取消星标')
                : getLabel(384242, '标记星标')
            }
            onClick={() => this.onCollect([id], starred ? 0 : 1)}
          />
          {/* <Dropdown overlay={fontSizeMenu}>
            <i className="icon-coms02-Font-setting" />
          </Dropdown> */}
          {/* eslint-disable */}
          <span onClick={() => setState({ isSimple: isSimple ^ 1 })}>
            {isSimple ? getLabel(34223, "完整") : getLabel(384288, "精简")}
            {getLabel(33361, "信息")}{" "}
            <i className={`icon-coms-${isSimple ? "down" : "up"}`} />
          </span>
          {/* eslint-enable */}
        </div>
      </div>,
      <div className={`${this.prefixClass}-base-to`}>
        <span>{getLabel(2046, '收件人')}:</span>
        <Collapse
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Collapse@uljsxe@collapseTo`}
          ref="collapseTo"
          reloadEmail={this.reloadEmail}
          datas={this.listArray(toJS(toSpan.list))}
        />
      </div>,
    ];
    ccSpan &&
      ccSpan.list &&
      ccSpan.list.length > 0 &&
      !isSimple &&
      list.push(
        <div className={`${this.prefixClass}-base-to`}>
          <span>{getLabel(17051, '抄送人')}:</span>
          <Collapse
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Collapse@p191we@collapseCc`}
            ref="collapseCc"
            reloadEmail={this.reloadEmail}
            datas={this.listArray(toJS(ccSpan.list))}
          />
        </div>,
      );
    if (!isSimple) {
      if (bccTipInfo) {
        list.push(
          <div className={`${this.prefixClass}-base-to`}>
            <span>{getLabel(81316, '密送人')}:</span>
            <p style={{ color: 'red' }}>{bccTipInfo}</p>
          </div>,
        );
      } else {
        bccSpan &&
          bccSpan.list &&
          bccSpan.list.length > 0 &&
          !isSimple &&
          list.push(
            <div className={`${this.prefixClass}-base-to`}>
              <span>{getLabel(81316, '密送人')}:</span>
              <Collapse
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Collapse@8mr9ql@collapseCc`}
                ref="collapseCc"
                reloadEmail={this.reloadEmail}
                datas={this.listArray(toJS(bccSpan.list))}
              />
            </div>,
          );
      }
    }

    list.push(
      <div className={`${this.prefixClass}-base-title`}>
        <Row
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Row@xxuifi@title`}
        >
          <Col
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Col@8km87z@showname`}
            span={classification && classificationSpan ? 21 : 24}
            className={`${this.prefixClass}-base-title-showname`}
          >
            {/* 发票识别状态 */}
            {emailOcrInvoiceStatus && (
              <span
                style={{
                  display: 'inline-block',
                  marginRight: 5,
                  minWidth: 14,
                }}
              >
                <i
                  title={
                    emailOcrInvoiceStatus === '1'
                      ? '发票已识别'
                      : '发票识别失败，点击可以再次识别。'
                  }
                  style={
                    emailOcrInvoiceStatus === '1'
                      ? {
                          color: '#1BDD3F',
                          'font-size': '18px',
                          cursor: 'pointer',
                        }
                      : {
                          color: '#F72B2B',
                          'font-size': '18px',
                          cursor: 'pointer',
                        }
                  }
                  className={
                    emailOcrInvoiceStatus === '1'
                      ? getFlagCls('invoice_right')
                      : getFlagCls('invoice_wrong')
                  }
                  onClick={this.onEmailOcrInvoiceClick}
                />
              </span>
            )}
            <span dangerouslySetInnerHTML={{ __html: subject }} />
            {op_showUnReadedCount ? (
              <span
                className={`${this.prefixClass}-base-title-unreadedcount`}
                onClick={() => this.onUnReadedListClick(id)}
              >
                {unReadedCount}
                {getLabel(384293, '个未查看')}
              </span>
            ) : null}
            {labels.map(({ color, name, id: tagId }) => (
              <WeaTag
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTag@wslrhz@tagId`}
                key={tagId}
                closable
                color={color}
                style={{ marginLeft: 5 }}
                title={name}
                onClose={() => this.onSetTag([id], tagId, 'removeLabel')}
              >
                {name}
              </WeaTag>
            ))}
          </Col>
          {classification && classificationSpan && (
            <Col
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Col@haohmq@classification`}
              span={3}
              className={`${this.prefixClass}-base-title-showsecrecy`}
            >
              {getLabel('515181', '密级：')}
              {classificationSpan}
            </Col>
          )}
        </Row>
      </div>,
    );
    count > 0 &&
      list.push(
        <div className={`${this.prefixClass}-base-files`}>
          {getLabel(18609, '共')}
          {count} {getLabel(83077, '个附件')}
          <a onClick={() => this.refs.scroll.scrollToLast()}>
            {getLabel(83124, '查看附件')}
          </a>
        </div>,
      );
    return list;
  }

  onBathDownload = () => {
    const {
      baseInfo: { fileInfos },
    } = this.getStoreNow();
    const { batchDownloadUrl } = fileInfos;
    window.open(batchDownloadUrl);
  };

  getFiles() {
    const {
      baseInfo: { fileInfos, unPreview },
    } = this.getStoreNow();
    if (!fileInfos) return null;
    const { fileList, count, totalSizeStr } = fileInfos;
    if (count === 0) return null;
    // console.log('toJS(fileList)', toJS(fileList))
    return [
      <div className={`${this.prefixClass}-files-title`}>
        <i className="icon-email-Enclosure" />
        {getLabel(156, '附件')}
        {count} {getLabel(27591, '个')}
        <span
          className={`${this.prefixClass}-files-title-batch-download`}
          onClick={this.onBathDownload}
        >
          <span>
            <i className="icon-coms-download" />
            {getLabel(32407, '批量下载')}
          </span>
          <span>({totalSizeStr})</span>
        </span>
      </div>,
      <div className={`${this.prefixClass}-files-list`}>
        {toJS(fileList).map((file) => {
          const {
            filelink,
            previewUrl,
            filename,
            filesize,
            fileid,
            isImg,
            fileExtendName,
          } = file;
          return (
            <div className={`${this.prefixClass}-files-list-item`} key={fileid}>
              <div className={`${this.prefixClass}-files-list-item-img`}>
                {isImg === 'true' ? (
                  /* eslint-disable */
                  <img
                    data-imgsrc={previewUrl}
                    ref={fileid}
                    src={previewUrl}
                    width={56}
                    height={56}
                    className="formImgPlay"
                    style={{ borderRadius: 4, cursor: "pointer" }}
                    onClick={
                      unPreview == "1"
                        ? () =>
                            message.warning(
                              getLabel(
                                "520702",
                                "后台邮件系统设置,禁止附件预览"
                              )
                            )
                        : viewer
                    }
                  />
                ) : (
                  /* eslint-enable */
                  <i
                    className={getFileTypeCls(fileExtendName)}
                    onClick={() => this.previewFile(file)}
                  />
                )}
              </div>
              <div className={`${this.prefixClass}-files-list-item-content`}>
                {isImg === 'true' ? (
                  <Tooltip
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_Tooltip@e9xr7a@imgfilename`}
                    title={filename}
                  >
                    <p>{filename}</p>
                  </Tooltip>
                ) : (
                  <Tooltip
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_Tooltip@vzxacw@filename`}
                    title={filename}
                  >
                    {/* eslint-disable */}
                    <p onClick={() => this.previewFile(file)}>{filename}</p>
                    {/* eslint-enable */}
                  </Tooltip>
                )}
                <p>{filesize}</p>
              </div>
              <div className={`${this.prefixClass}-files-list-item-ops`}>
                <Tooltip
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Tooltip@sm0wyr@download`}
                  title={getLabel(31156, '下载')}
                >
                  <i
                    className="icon-coms-download"
                    onClick={() => window.open(filelink)}
                  />
                </Tooltip>
                <Tooltip
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Tooltip@8qrqga@savetocloud`}
                  title={getLabel(129159, '保存到云盘')}
                >
                  <i
                    className="icon-email-Save-the-cloud-disk"
                    style={{ display: 'none' }}
                  />
                </Tooltip>
              </div>
            </div>
          );
        })}
      </div>,
    ];
  }

  previewFile = (file) => {
    // const { router } = this.context;
    // router.push(`/main/preview?fileid=${file.id}`); // 调试用
    const { baseInfo } = this.getStoreNow();
    const { unPreview } = baseInfo;
    if (unPreview == '1') {
      // 禁止预览
      message.warning(getLabel('520702', '后台邮件系统设置,禁止附件预览'));
    } else {
      const previewurl = `/spa/email/static/index.html#/main/preview?fileid=${file.id}`;
      openFullWindowHaveBar(previewurl);
    }
  };

  onCancelShowReply = () =>
    this.getStoreNow().setState({ showQuickReplay: false });

  getQuickReply() {
    const { router } = this.context;
    const {
      id,
      baseInfo,
      baseInfo: { isInternal },
      showQuickReplay,
      replycontent,
      setState,
      fastReplyLoading,
      doFastReply,
    } = this.getStoreNow();
    if (!baseInfo.fromSpan) return null;
    // props.style cannot be render in WeaTextarea...
    return (
      <div className={`${this.prefixClass}-quick-reply`}>
        <div style={{ display: showQuickReplay ? 'block' : 'none' }}>
          <WeaTextarea
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTextarea@cb5meo`}
            ref="quickreply"
            value={replycontent}
            onChange={v => setState({ replycontent: v })}
            minRows={4}
            maxRows={4}
          />
          <div style={{ padding: '10px 0' }}>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@q3piq2`}
              type="primary"
              onClick={() =>
                doFastReply({
                  mailId: id,
                  replycontent: `<div style='white-space: pre-wrap'>${replycontent}</div>`,
                }).then((res) => {
                  res.status === '1' &&
                    setState({ showQuickReplay: false, replycontent: '' });
                })
              }
              loading={fastReplyLoading}
              disabled={!replycontent || String(baseInfo.sendcount) === '0'}
              title={
                replycontent && String(baseInfo.sendcount) === '0'
                  ? getLabel(
                      '511710',
                      '已超出允许的收件人数，请删除部分收件人或分批发送',
                    )
                  : ''
              }
            >
              {getLabel(2083, '发送')}
            </Button>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@g77gs3`}
              style={{ marginLeft: 14 }}
              type="ghost"
              onClick={this.onCancelShowReply}
            >
              {getLabel(31129, '取消')}
            </Button>
            <span
              className={`${this.prefixClass}-quick-reply-tofull`}
              onClick={() =>
                router.push({
                  pathname: 'main/email/new',
                  query: { isInternal, id, flag: 1 },
                })
              }
            >
              <span style={{ 'text-align': 'right', cursor: 'pointer' }}>
                {getLabel(83125, '切换到完整写信模式')}
              </span>
            </span>
          </div>
        </div>
        <div
          className={`${this.prefixClass}-quick-reply-btn`}
          style={{ display: showQuickReplay ? 'none' : 'block' }}
          onClick={() => {
            setState({ showQuickReplay: true });
            this.quickTimer = setTimeout(() => {
              $(ReactDOM.findDOMNode(this.refs.quickreply))
                .find('textarea')
                .focus();
              this.refs.scroll.scrollToLast();
              this.quickTimer && clearTimeout(this.quickTimer);
            }, 50);
          }}
        >
          <i className="icon-email-Write-letters" />{' '}
          {getLabel(32110, '快捷回复')}
        </div>
      </div>
    );
  }
  // 获取分别发送结果列表
  getApartSendingResultList = () => {
    const storeNow = this.getStoreNow();
    const {
      id,
      location: {
        pathname,
        query: { id: _id },
      },
    } = this.props;
    const {
      baseInfo: { isSendApart, isInternal },
      sendApartResultList,
      isSendApartResultListVis,
      setState,
      sendStatus,
    } = storeNow;
    // 获取当前正在查看的邮件id，init表示当前没有正在查看的邮件id
    const curViewedMailId = id || _id || 'init';

    const _path = pathname.replace('main/email/', '').split('/')[0];
    // 要满足条件：1.分别发送 2.已发送 3.外部邮件 4.sendApartResultList有值
    if (
      (_path !== 'sent' && _path !== 'view') ||
      curViewedMailId === 'init' ||
      isInternal === 1 ||
      isSendApart !== 1 ||
      sendApartResultList.length === 0
    ) {
      return null;
    }
    const columns = [
      {
        title: getLabel(2046, ' 收件人'),
        dataIndex: 'sendto',
      },
      {
        title: getLabel(384295, '投递状态'),
        dataIndex: 'sendstatus',
      },
      {
        title: getLabel(25130, '时间'),
        dataIndex: 'senddate',
      },
    ];
    const datas = toJS(sendApartResultList).map((elem, index) => ({
      key: index + elem.sendto,
      sendto: elem.sendto,
      sendstatus:
        elem.sendstatus === '2'
          ? getLabel(384296, '投递失败')
          : getLabel(384297, '投递成功'),
      senddate: elem.senddate,
    }));
    return (
      <div style={{ minHeight: 'auto' }}>
        <div style={{ minHeight: 'auto', lineHeight: 3 }}>
          <span style={{ color: '#666' }}>
            {getLabel(384298, '发送状态：')}
          </span>
          <span style={{ color: '#f00' }}>
            {sendStatus === '0'
              ? getLabel(385608, '全部投递成功')
              : sendStatus === '1'
              ? getLabel(385609, '全部投递失败')
              : sendStatus === '2'
              ? getLabel(384299, '部分投递成功')
              : null}
          </span>
          <a
            href="javascript:;"
            style={{ marginLeft: 10 }}
            onClick={() => {
              setState({
                isSendApartResultListVis: !isSendApartResultListVis,
              });
            }}
          >
            {isSendApartResultListVis
              ? getLabel(384300, '关闭详情')
              : getLabel(83110, '查看详情')}
          </a>
        </div>
        <Table
          ecId={`${(this && this.props && this.props.ecId) || ''}_Table@wqxhu7`}
          ref="sendApartResultList"
          style={{ display: isSendApartResultListVis ? 'block' : 'none' }}
          columns={columns}
          dataSource={datas}
          pagination={false}
          size="small"
        />
      </div>
    );
  };
  // 获取撤回结果列表
  getRecallDetailList = () => {
    const storeNow = this.getStoreNow();
    const {
      id,
      location: {
        pathname,
        query: { id: _id },
      },
    } = this.props;
    const {
      baseInfo: { isInternal, recallstate },
      emailRecallDetailList,
      isEmailRecallDetailListVis,
      setState,
      recallStatus,
      recallRule,
      recallNoTrace,
    } = storeNow;
    // 获取当前正在查看的邮件id，init表示当前没有正在查看的邮件id
    const curViewedMailId = id || _id || 'init';
    const _path = pathname.replace('main/email/', '').split('/')[0];
    if (
      ((_path === 'sent' ||
        _path === 'inner' ||
        _path === 'doing' ||
        _path === 'star' ||
        _path === 'folder' ||
        _path === 'tag' ||
        _path === 'deleted' ||
        _path === 'inbox') &&
        curViewedMailId !== 'init' &&
        isInternal === 1 &&
        recallstate === 1 &&
        emailRecallDetailList.length !== 0) ||
      (_path === 'view' &&
        curViewedMailId !== 'init' &&
        isInternal === 1 &&
        recallstate === 1 &&
        emailRecallDetailList.length !== 0)
    ) {
      const columns = [
        {
          title: getLabel(2046, ' 收件人'),
          dataIndex: 'mailreceiver',
          width: 150,
        },
        {
          title: getLabel(510118, '撤回时阅读状态'),
          dataIndex: 'readstatus',
          width: 150,
        },
        {
          title: getLabel(505368, '撤回状态'),
          dataIndex: 'recallstatus',
          width: 150,
        },
        {
          title: getLabel(277, ' 时间'),
          dataIndex: 'recalldate',
          width: 150,
        },
      ];
      const datas = toJS(emailRecallDetailList).map((elem, index) => ({
        key: index + elem.mailreceiver,
        mailreceiver: elem.mailreceiver,
        readstatus:
          elem.readstatus === '1'
            ? getLabel(18006, '已查看')
            : (elem.readstatus === '2' ? getLabel(524041, '已标记为已读，但未查看') : getLabel(81883, '未查看')),
        recallstatus:
          elem.recallstatus === '1' ? (
            <span style={{ color: 'red' }}>{getLabel(505791, '撤回失败')}</span>
          ) : (
            <span style={{ color: 'green' }}>
              {getLabel(505793, '撤回成功')}
            </span>
          ),
        recalldate: elem.recalldate,
      }));
      return (
        <div style={{ minHeight: 'auto' }}>
          <div style={{ minHeight: 'auto', lineHeight: 3 }}>
            <span style={{ color: '#666' }}>
              {getLabel(505368, '撤回状态')}：
            </span>
            <span style={{ color: '#f00' }}>
              {recallStatus === '0'
                ? getLabel(505369, '全部撤回成功')
                : recallStatus === '1'
                ? getLabel(505794, '全部撤回失败')
                : recallStatus === '2'
                ? getLabel(505370, '部分撤回成功')
                : null}
            </span>
            <a
              href="javascript:;"
              style={{ marginLeft: 10 }}
              onClick={() => {
                setState({
                  isEmailRecallDetailListVis: !isEmailRecallDetailListVis,
                });
              }}
            >
              {isEmailRecallDetailListVis
                ? getLabel(384300, '关闭详情')
                : getLabel(83110, '查看详情')}
            </a>
            <span style={{ color: '#666', paddingLeft: 15 }}>
              ({getLabel(505363, '撤回规则')}:{recallRule}
              {recallNoTrace === '' ? '' : `,${recallNoTrace}`})
            </span>
          </div>
          <Table
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Table@k6ote9`}
            ref="emailRecallDetailList"
            style={{ display: isEmailRecallDetailListVis ? 'block' : 'none' }}
            columns={columns}
            dataSource={datas}
            pagination={false}
            size="small"
            scroll={{ y: 310 }}
          />
        </div>
      );
    }
    return null;
  };

  getDropDown = () =>
    toJS(this.getStoreNow().dropDown).map((d, index) => (
      <DropdownMenu
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_DropdownMenu@oqfk35@emialdropdown${index}`}
        data={d}
        onClick={this.onDropDownClick}
        type="custom"
      />
    ));
  getAlertPage = (iconCls, text) => {
    let alertProps = { iconSize: 100 };
    if (iconCls) {
      alertProps = {
        ...alertProps,
        icon: <i className={iconCls} style={{ color: '#999' }} />,
        iconSize: 40,
      };
    }
    return (
      <div className={`${this.prefixClass} ${this.prefixClass}-null`}>
        <WeaAlertPage
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaAlertPage@w643lh`}
          {...alertProps}
        >
          <div style={{ color: '#999', marginTop: 16 }}>{text}</div>
        </WeaAlertPage>
      </div>
    );
  };

  receiveNeedReceipt = (mailId) => {
    const { emailCommonOperation } = this.getStoreNow();
    confirm({
      title: getLabel(15172, '系统提示'),
      content: getLabel(32473, '发件人希望得到您的回执，是否发送？'),
      onOk() {
        emailCommonOperation({ mailId, operateType: 'receiveNeedReceipt' });
      },
      onCancel() {
        emailCommonOperation({ mailId, operateType: 'readReceipt' });
      },
    });
  };

  onNewScroll = () => this.hide(true);
  onIconClick = () => this.props.emailMainStore.setState({ viewId: 'init' });
  openInNewTab = () => {
    const { router } = this.context;
    const { emailMainStore } = this.props;
    const { id } = this.getStoreNow();
    router.push(`main/email/view?id=${id}`);
    emailMainStore.setState({ viewIdInTab: id });
  };
  render() {
    const { emailScroll } = this.state;
    const { viewType } = this.props;
    const storeNow = this.getStoreNow();
    const {
      right,
      rightLoading,
      id,
      content,
      baseLoading,
      classificationRight,
      baseInfo: {
        subject,
        isSender,
        recallstate,
        folderid,
        fromSpan,
        belongtoType,
      },
    } = storeNow;
    const opsCls = classnames({
      [`${this.prefixClass}-ops`]: true,
      emailScroll,
    });

    if (id === 'init') {
      return this.getAlertPage(
        'icon-email-withdrawal',
        getLabel(384302, '请选择需要查看的邮件'),
      );
    }
    if (right !== 1) {
      if (right === -1) {
        return rightLoading ? (
          <Spin
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Spin@0lmzbc`}
            spinning={rightLoading}
          >
            <div style={{ height: 300 }} />
          </Spin>
        ) : (
          this.getAlertPage(
            'icon-email-error',
            getLabel(390255, '该邮件已被删除'),
          )
        );
      }
      return rightLoading ? (
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@ai8suw`}
          spinning={rightLoading}
        >
          <div style={{ height: 300 }} />
        </Spin>
      ) : (
        this.getAlertPage(
          'icon-email-error',
          getLabel(385529, '无权查看该邮件'),
        )
      );
    }

    if (right && !classificationRight) {
      return rightLoading ? (
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@8etxn4`}
          spinning={rightLoading}
        >
          <div style={{ height: 300 }} />
        </Spin>
      ) : (
        this.getAlertPage('', '对不起，您的人员密集不足以查看该内容')
      );
    } else if (right && classificationRight) {
      return (
        <div className={this.prefixClass}>
          <div className={opsCls}>
            {this.getDropDown()}
            {viewType === 'inList' && (
              <div className={`${this.prefixClass}-ops-right`}>
                <i
                  className="icon-email-Open"
                  title={getLabel(384303, '在新标签中打开')}
                  onClick={this.openInNewTab}
                />
                <Icon
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Icon@c0qdk4`}
                  type="cross"
                  title={getLabel(309, '关闭')}
                  onClick={this.onIconClick}
                />
              </div>
            )}
          </div>
          <div className={`${this.prefixClass}-scroll`}>
            <WeaNewScroll
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaNewScroll@hv8eq6`}
              ref="scroll"
              height="100%"
              className={`${this.prefixClass}-scroll-container`}
              onScroll={this.onNewScroll}
              toTop={true}
            >
              <div
                className={`${this.prefixClass}-main`}
                ref={`weaNewView_${id}`}
                id={this.printId}
              >
                <Spin
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Spin@qjw4qt`}
                  spinning={baseLoading && subject === undefined}
                >
                  <div className={`${this.prefixClass}-base`}>
                    {this.getBase()}
                  </div>
                </Spin>
                {this.getApartSendingResultList()}
                {this.getRecallDetailList()}

                <div className={`${this.prefixClass}-content`}>
                  {isSender === 0 && belongtoType == '' && recallstate === 1 ? (
                    this.getAlertPage(
                      'icon-email-withdrawal',
                      getLabel(32063, '发信方已撤回邮件'),
                    )
                  ) : (
                    <ContentIframe
                      ecId={`${
                        (this && this.props && this.props.ecId) || ''
                      }_ContentIframe@asd32k`}
                      ref="content"
                      value={content}
                      onClick={this.onIframeClick}
                    />
                  )}
                </div>
                <div className={`${this.prefixClass}-files`}>
                  {this.getFiles()}
                </div>
                {fromSpan &&
                  fromSpan.hrmId !== '1' &&
                  folderid !== '-1' &&
                  folderid !== '-3' &&
                  this.getQuickReply()}
              </div>
            </WeaNewScroll>
            {(isSender === 1 || belongtoType != '') && recallstate === 1 ? (
              <div className={`${this.prefixClass}-recall`}>
                {getLabel(384304, '已撤回邮件')}
              </div>
            ) : null}
          </div>
        </div>
      );
    }
  }
}

export default View;
